package middleware.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * zk 客户端连接工具类
 *
 * @Title: com.ccssoft.provision.web.config.manager.ZooKeeperConnection
 * @author ME
 * @date 2018年10月29日 上午10:39:15
 */
public class ZooKeeperConnection implements AutoCloseable {

	private ZooKeeper zookeeperClient;

	/**
	 * 借助成员变量 `zookeeperClient` 和 Try-with-resources机制 实现会话自动关闭
	 */
	public ZooKeeperConnection() {
	}

	public ZooKeeper connect(String host) throws IOException, InterruptedException {
		// 连接服务器，并注册 ZooKeeper客户端的连接事件
		zookeeperClient = new ZooKeeper(host, 1000, new Watcher() {
			@Override
			public void process(WatchedEvent we) {
				if (we.getState() == KeeperState.SyncConnected) {
					System.out.println("KeeperState：客户端连接状态~~");
				} else if (we.getState() == KeeperState.Disconnected) {
					System.out.println("KeeperState：客户端处于断开连接状态");
				} else if (we.getState() == KeeperState.SaslAuthenticated) {
					System.out.println("KeeperState：通知客户端它们已通过SASL认证，以便它们可以使用其SASL授权的权限执行Zookeeper操作");
				} else if (we.getState() == KeeperState.AuthFailed) {
					System.out.println("KeeperState：验证失败状态~~");
				} else if (we.getState() == KeeperState.Expired) {
					System.out.println("KeeperState：通知此会话已过期，ZooKeeper客户端连接（会话）不再有效。如果要访问，必须创建一个新的客户端连接");
				}
			}
		});

		return zookeeperClient;
	}

	@Override
	public void close() throws InterruptedException {
		System.out.println("自动关闭 zookeeper 连接~~");

		zookeeperClient.close();
	}

}
